package com.n5x.controller.admin.shopping;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.n5x.common.base.JsonModel;
import com.n5x.common.base.ResponseCode;
import com.n5x.common.base.TokenModel;
import com.n5x.common.util.StringUtil;
import com.n5x.controller.BaseController;
import com.n5x.model.admin.AdminUser;
import com.n5x.model.goods.GoodsInfo;
import com.n5x.model.shopping.ShoppingCart;
import com.n5x.model.shopping.ShoppingOrder;
import com.n5x.model.shopping.ShoppingOrderDetails;
import com.n5x.service.IAdminService;
import com.n5x.service.IGoodsService;
import com.n5x.service.IShoppingService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 前台购物车接口
 * 需要用户token
 */
@Controller("adminOrder")
@RequestMapping("/admin/shopping/order")
public class OrderController extends BaseController {

    @Autowired
    public HttpServletRequest request;

    @Autowired
    private IGoodsService iGoodsService;

    @Autowired
    private IShoppingService iShoppingService;

    @Autowired
    private IAdminService iAdminService;

    @InitBinder("shoppingOrder")
    public void initBinderShoppingOrder(WebDataBinder binder) {
        binder.setFieldDefaultPrefix("shoppingOrder.");
    }

    @RequestMapping(value = "/list", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public JsonModel list() {
        try {
            String token = request.getParameter("token");
            String id = request.getParameter("id");
            String receiptCode = request.getParameter("receiptCode");
            String pageNum = request.getParameter("pageNum");
            String pageSize = request.getParameter("pageSize");
            String beginTime = request.getParameter("beginTime");
            String endTime = request.getParameter("endTime");
            String deliver = request.getParameter("deliver");
            String userName = request.getParameter("userName");
            String currentState = request.getParameter("currentState");
            String method = request.getParameter("method");
            TokenModel tokenModel = getTokenModelByToken(token);
            String userId = tokenModel.getUserId();
            Map pararm = new HashMap();
            pararm.put("id", id);
            pararm.put("receiptCode", receiptCode);
            pararm.put("userName", StringUtil.isBlank(userName) ? null : "%" + userName + "%");
            pararm.put("beginTime", beginTime);
            pararm.put("endTime", endTime);
            pararm.put("deliver", deliver);
            pararm.put("method",method);
            if (StringUtils.isNotBlank(currentState)) {
                String[] states = currentState.split(",");
                pararm.put("currentState", Arrays.asList(states));
            }
            AdminUser adminUser = iAdminService.findAdminUser(userId);
            if (adminUser == null) {
                return getResult(ResponseCode.Common_ParamError, "找不到送货员信息");
            }
            if (adminUser.getType().equals(AdminUser.Type.送货员.name())) {
                pararm.put("deliver", userId);
            }
            int count = iShoppingService.countUserShopingOrder(pararm);
            Page page = null;
            if (pageNum != null && pageSize != null) {
                page = PageHelper.startPage(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
            }


            logger.info("[后台查询订单]pararm:{}", pararm);
            List<ShoppingOrder> list = iShoppingService.selectUserShopingOrder(pararm);

            if (null!=page){
                PageInfo info = new PageInfo(page);
                Long total = info.getTotal();
            }
            if (CollectionUtils.isEmpty(list)) {
                return getResult(ResponseCode.Common_DataNotFound, "找不到订单信息");
            }
            return getResult(list).setResult(String.valueOf(count));
        } catch (Exception e) {
            logger.error("[后台查询订单失败]e:{}", new Object[]{e.toString()});
            e.printStackTrace();
            return getResultError(ResponseCode.Common_Error, e.toString());
        }
    }

    @RequestMapping(value = "/info", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public JsonModel info(@RequestParam(value = "token", required = false) String token, @RequestParam(value = "id", required = false) String id) {
        try {
            if (StringUtils.isBlank(id)) {
                return getResultError(ResponseCode.Common_ParamError, "订单ID不能为空");
            }
            ShoppingOrder shoppingOrder = iShoppingService.findShoppingOrder(id);
            if (shoppingOrder == null) {
                return getResultError(ResponseCode.Common_DataNotFound, "订单不存在");
            }
            return getResult(shoppingOrder);
        } catch (Exception e) {
            logger.error("[生成商品订单失败]e:{}", new Object[]{e.toString()});
            e.printStackTrace();
            return getResultError(ResponseCode.Common_Error, e.toString());
        }
    }

    @RequestMapping(value = "/updateState", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public JsonModel update() {
        try {
            String id = request.getParameter("id");
            String state = request.getParameter("state");
            String deliver = request.getParameter("deliver");
            logger.info("[修改订单状态]id:{},state:{},deliver:{}", new Object[]{id, state, deliver});
            if (StringUtils.isBlank(id)) {
                return getResultError(ResponseCode.Common_ParamError, "订单ID不能为空");
            }
            ShoppingOrder shoppingOrder = iShoppingService.findShoppingOrder(id);
            if (shoppingOrder == null) {
                return getResultError(ResponseCode.Common_ParamError, "订单不存在");
            }
            shoppingOrder.setCurrentState(state);
            if (state.equals(ShoppingOrder.ShoppingState.派单.getState())) {
                shoppingOrder.setDeliver(deliver);
            }
            if (state.equals(ShoppingOrder.ShoppingState.完成.getState())) {
                shoppingOrder.setFinishTime(new Date());
            }
            shoppingOrder = iShoppingService.saveShoppingOrder(shoppingOrder, null);
            return getResult(shoppingOrder.getId());
        } catch (Exception e) {
            logger.error("[修改订单状态失败]e:{}", new Object[]{e.toString()});
            e.printStackTrace();
            return getResultError(ResponseCode.Common_Error, e.toString());
        }
    }

    @RequestMapping(value = "/create")
    @ResponseBody
    public JsonModel create(String params) {
        try {
            String userId = request.getParameter("userId");
            String goodsArray = request.getParameter("goodsArray");
            Gson gs = new Gson();
            List<ShoppingCart> shoppingCarts = gs.fromJson(goodsArray, new TypeToken<List<ShoppingCart>>() {
            }.getType());
            logger.info("[后台生成商品订单]");
            List<String> nullList = new ArrayList<String>();
            List<String> disableList = new ArrayList<String>();
            List<ShoppingOrderDetails> orderDetails = new ArrayList<ShoppingOrderDetails>();
            for (ShoppingCart shoppingCart : shoppingCarts) {
                GoodsInfo goodsInfo = iGoodsService.findGoodsInfo(shoppingCart.getFkGoods());
                if (goodsInfo.getDisable() != null && goodsInfo.getDisable() == true) {
                    disableList.add(goodsInfo.getId());
                    continue;
                }
                if (goodsInfo.getQty() == 0) {
                    nullList.add(goodsInfo.getId());
                    continue;
                }
                ShoppingOrderDetails shoppingOrderDetails = new ShoppingOrderDetails(goodsInfo, shoppingCart.getQty());
                orderDetails.add(shoppingOrderDetails);
            }
            if (CollectionUtils.isNotEmpty(nullList)) {
                JsonModel jsonModel = getResultError(ResponseCode.Common_DataNotFound, "商品库存为空");
                jsonModel.setData(nullList);
                return jsonModel;
            }
            if (CollectionUtils.isNotEmpty(disableList)) {
                JsonModel jsonModel = getResultError(ResponseCode.Common_DataNotFound, "商品已下架");
                jsonModel.setData(disableList);
                return jsonModel;
            }
            ShoppingOrder shoppingOder = iShoppingService.saveNewShoppingOrderByGoods(userId, orderDetails);
            if (shoppingOder == null) {
                return getResult(ResponseCode.Common_Fail, "订单创建失败");
            }
            return getResult(shoppingOder.getId());
        } catch (Exception e) {
            logger.error("[生成商品订单失败]e:{}", new Object[]{e.toString()});
            e.printStackTrace();
            return getResultError(ResponseCode.Common_Error, e.toString());
        }
    }
}